<?php

function load_config() {
	global $g_config;

	$result = mysql_query("SELECT id, value FROM mail_config");
	while ($row = mysql_fetch_assoc($result)) {
		$g_config[$row['id']] = $row['value'];
	}
}

function _log() {
	ChromePhp::log(func_get_args());
}

function db_escape($str) {
	global $g_conn;

	return mysql_real_escape_string($str, $g_conn);
}

function get_web_mail() {
	$web_mails = array();

	$sql = "SELECT web_mail_id, name, description, path FROM web_mail";
	$result = mysql_query($sql);

	while ($row = mysql_fetch_assoc($result)) {
		$web_mails[] = $row;
	}

	return $web_mails;
}

function get_groups() {
	$groups = array();

	$group_sql = "SELECT friend_group_id, name FROM friend_group";
	$result = mysql_query($group_sql);
	while ($row = mysql_fetch_assoc($result)) {
		$groups[] = $row;
	}

	return $groups;
}

function get_group_of_friend($friend_id) {
	$groups = array();

	$sql = "SELECT friend_group_id FROM friend_to_friend_group WHERE friend_id=%d";
	$sql2 = "SELECT friend_group_id, name FROM friend_group WHERE friend_group_id=%d";

	// Lấy id của các group mà friend thuộc
	$result = mysql_query(sprintf( $sql, intval($friend_id) ));
	while ($row = mysql_fetch_assoc($result)) {
		// Lấy thông tin group
		$result2 = mysql_query(sprintf( $sql2, intval($row['friend_group_id']) ));
		while ($row2 = mysql_fetch_assoc($result2)) {
			$groups[] = $row2;
		}
	}

	return $groups;
}

function parseMixedContact($mixed_str) {
	$contacts = array();

	// Lấy group
	if (preg_match_all('/\[(\d+):Group]/', $mixed_str, $tgroup)) {
		$contacts['group'] = $tgroup[1];
		$mixed_str = preg_replace('/\[(\d+):Group]/', '', $mixed_str);
	}

	// Lấy friend
	if (preg_match_all('/\[(\d+):Friend:[^\]]+\]/', $mixed_str, $tfriend)) {
		$contacts['friend'] = $tfriend[1];
		$mixed_str = preg_replace('/\[(\d+):Friend:[^\]]+\]/', '', $mixed_str);
	}

	// Lấy mail
	if (preg_match_all('/\b([a-zA-Z0-9])+([a-zA-Z0-9\._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+\b/', $mixed_str, $tmail)) {
		$contacts['mail'] = $tmail[0];
	}

	return $contacts;
}

function parseReceiver($parsed) {
	$to = array();

	// friend
	if (isset($parsed['friend'])) {
		$sql = "SELECT friend_id, mail FROM friend WHERE friend_id IN (%s)";
		$result = mysql_query(sprintf( $sql, implode(',', $parsed['friend']) ));
		while ($row = mysql_fetch_assoc($result)) {
			$to[] = $row['mail'];
		}		
	}

	// group
	if (isset($parsed['group'])) {		
		// Lấy id của các friend
		$fids = array();
		$sql = "SELECT DISTINCT friend_id FROM friend_to_friend_group WHERE friend_group_id IN (%s)";
		$result = mysql_query(sprintf( $sql, implode(',', $parsed['group']) ));
		while ($row = mysql_fetch_assoc($result)) {
			$fids[] = $row['friend_id'];
		}

		// Lấy mail của friend thuộc group
		if (!empty($fids)) {
			$sql = "SELECT friend_id, mail FROM friend WHERE friend_id IN (%s)";
			$result = mysql_query(sprintf( $sql, implode(',', $fids) ));
			while ($row = mysql_fetch_assoc($result)) {
				$to[] = $row['mail'];
			}			
		}
	}

	// Mail
	if (isset($parsed['mail'])) {
		$to = array_unique( array_merge($to, $parsed['mail']) );
	}

	return $to;
}

function addSentContact($mail_id, $parsed, $type = 'to') {
	// group
	if (isset($parsed['group'])) {
		$sql = "INSERT INTO sent_mail_to_contact(sent_mail_id, friend_group_id, type) VALUES(%d, %d, '%s')";
		foreach ($parsed['group'] as $group_id) {
			$q = sprintf( $sql, intval($mail_id), intval($group_id), $type );
			mysql_query($q) OR _log('Could not run query: ' . $q);
		}		
	}

	// friend
	if (isset($parsed['friend'])) {
		$sql = "INSERT INTO sent_mail_to_contact(sent_mail_id, friend_id, type) VALUES(%d, %d, '%s')";
		foreach ($parsed['friend'] as $friend_id) {
			$q = sprintf( $sql, intval($mail_id), intval($friend_id), $type );
			mysql_query($q) OR _log('Could not run query: ' . $q);		
		}		
	}

	// mail
	if (isset($parsed['mail'])) {
		$sql = "INSERT INTO sent_mail_to_contact(sent_mail_id, mail, type) VALUES(%d, '%s', '%s')";
		foreach ($parsed['mail'] as $mail) {
			$q = sprintf( $sql, intval($mail_id), db_escape($mail), $type );
			mysql_query($q) OR _log('Could not run query: ' . $q);		
		}
	}
}

function getReceivedContact($sent_mail_id) {
	$contacts = array(
		'to' => array(),
		'cc' => array(),
		'bcc' => array()
	);

	// Lấy contact
	$sql = "SELECT s.friend_group_id, s.friend_id, s.mail, s.type, fg.name, f.fullname FROM sent_mail_to_contact s";
	$sql .= " LEFT JOIN friend_group fg ON s.friend_group_id = fg.friend_group_id";
	$sql .= " LEFT JOIN friend f ON s.friend_id = f.friend_id";
	$sql .= " WHERE sent_mail_id=" . intval($sent_mail_id);
	$result = mysql_query($sql) or _log('Error query: ' . $sql);
	while ($row = mysql_fetch_assoc($result)) {
		if ($row['type'] == 'to') {
			$contacts['to'][] = $row;
		} elseif ($row['type'] == 'cc') {
			$contacts['cc'][] = $row;
		} elseif ($row['type'] == 'bcc') {
			$contacts['bcc'][] = $row;
		}
	}

	return $contacts;
}